package com.forest.core.util

import android.annotation.SuppressLint
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.wifi.WifiManager
import android.os.Build
import android.telephony.TelephonyManager
import android.telephony.TelephonyManager.SIM_STATE_READY
import com.forest.core.etx.screenHeight
import com.forest.core.etx.toast
import java.util.*


@SuppressLint("StaticFieldLeak")
object DeviceUtil {

    private const val MAC_ADDRESS_KEY = "macAddress"

    private const val IMEI_KEY = "imei"

    const val PACKAGE_UC_BROWSER = "com.UCMobile"

    const val PACKAGE_QQ_BROWSER = "com.tencent.mtt"

     const val WX_PACKAGE_NAME = "com.tencent.mm"
     const val LAUNCHER_UI = "com.tencent.mm.ui.LauncherUI"
     const val SHARE_IMG_UI = "com.tencent.mm.ui.tools.ShareImgUI"
     const val SHARE_TO_TIMELINE_UI = "com.tencent.mm.ui.tools.ShareToTimeLineUI"

    private var mac: String by Preference(MAC_ADDRESS_KEY, "")

    private var imeiId: String by Preference(IMEI_KEY, "")

    private lateinit var mContext: Context

    fun setContext(context: Context) {
        mContext = context
    }

    //获得独一无二的UniqueId
    private fun getUniqueId(): String {
        var serial = ""
        val uniqueId = "35" +
                Build.BOARD.length % 10 + Build.BRAND.length % 10 +

                Build.CPU_ABI.length % 10 + Build.DEVICE.length % 10 +

                Build.DISPLAY.length % 10 + Build.HOST.length % 10 +

                Build.ID.length % 10 + Build.MANUFACTURER.length % 10 +

                Build.MODEL.length % 10 + Build.PRODUCT.length % 10 +

                Build.TAGS.length % 10 + Build.TYPE.length % 10 +

                Build.USER.length % 10 //13 位

        try {
            serial = Build.SERIAL
            if (serial.isEmpty()) {
                serial = Build::class.java.getField("SERIAL").get(null).toString()
            }
            //API>=9 使用serial号
            return UUID(uniqueId.hashCode().toLong(), serial.hashCode().toLong()).toString()
        } catch (exception: Exception) {
            //serial需要一个初始化
            serial = "serial"
        }

        //使用硬件信息拼凑出来的15位号码
        return UUID(uniqueId.hashCode().toLong(), serial.hashCode().toLong()).toString()
    }

    @SuppressLint("HardwareIds")
    fun getMacAddress(): String {
        val wifiInfo = (mContext.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager).connectionInfo
        wifiInfo?.run {
            if (mac.isEmpty()) {
                mac = try {
                    if (macAddress.isEmpty()) {
                        getUniqueId()
                    } else {
                        macAddress
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    getUniqueId()
                }
            }
        }
        return mac
    }

    fun getImei(): String {
        if (imeiId.isEmpty()) {
            imeiId = getUniqueId()
        }
        return imeiId
    }

    fun getPackageName(): String {
        return mContext.packageName
    }

    fun getAppName(): String {
        mContext.packageManager.getPackageInfo(getPackageName(), 0)?.run {
            return mContext.resources.getString(applicationInfo.labelRes)
        }
        return ""
    }

    fun getAppVersionCode(): Int {
        mContext.packageManager.getPackageInfo(getPackageName(), 0)?.run {
            return versionCode
        }
        return 0
    }

    fun getAppVersionName(): String {
        mContext.packageManager.getPackageInfo(getPackageName(), 0)?.run {
            return if (versionName.isEmpty()) "1.0.0" else versionName
        }
        return "1.0.0"
    }

    fun getDevice(): String {
        return Build.DEVICE
    }

    fun getBrand(): String {
        return Build.BRAND
    }

    fun getModel(): String {
        return Build.MODEL
    }

    fun getOSVersion(): String {
        return Build.VERSION.RELEASE
    }

    fun getOSName(): String {
        return Build.VERSION.CODENAME
    }

    fun getSimOperator(): String{
        var returnSimOperator = ""
        val tm = mContext.applicationContext.getSystemService(Context.TELEPHONY_SERVICE) as? TelephonyManager
        tm?.apply {
            if(simState == SIM_STATE_READY){
                val getSimOperator = simOperator
                if(!getSimOperator.isNullOrEmpty()){
                    returnSimOperator = getSimOperator
                }
            }
        }
        return returnSimOperator
    }

    fun getPixels(context: Context): String {
        return "${context.screenHeight}*${context.screenHeight}"
    }

    fun isInstall(context: Context,packageName:String): Boolean{
        context.packageManager.getInstalledPackages(0)
                ?.filter { it.packageName.equals(packageName, true) }
                ?.let { return it.isNotEmpty() }
        return false
    }

    fun startWeChatActivity(context: Context) {
        try {
            Intent(Intent.ACTION_MAIN).run {
                addCategory(Intent.CATEGORY_LAUNCHER)
                addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                component = ComponentName(WX_PACKAGE_NAME, LAUNCHER_UI)
                (context as Activity).startActivity(this)
            }
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            context.toast("未安装微信客户端,请安装微信客户端后再进行分享。")
        }
    }

    /**
     * 跳转到拨号界面
     */
    fun startCallActivity(context: Context, phoneNumber: String) {
        try {
            val dialIntent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:$phoneNumber"))//跳转到拨号界面，同时传递电话号码
            context.startActivity(dialIntent)
        } catch (e: ActivityNotFoundException) {
            e.printStackTrace()
            context.toast("权限已拒绝")
        }
    }

}